<template>
  <div class="bigbox">
    <div class="topbox">
      <el-form
        :model="form"
        ref="form"
        label-position="left"
        label-width="80px"
        onsubmit="return false"
      >
        <el-row :gutter="20">
          <el-col :span="5">
            <el-form-item label="用电企业">
              <FilterSelect2
                v-model="form.companyId"
                :optionlist="companyList"
                :valuekey="{ name: 'name', value: 'id' }"
                @changeSelect="companyChange"
              ></FilterSelect2>
            </el-form-item>
          </el-col>
          <el-col :span="6" style="text-align: left">
            <el-radio-group
              size="small"
              v-model="radio"
              style="margin-right: 20px"
            >
              <el-radio-button label="日"></el-radio-button>
              <el-radio-button label="月"></el-radio-button>
              <el-radio-button label="年"></el-radio-button>
            </el-radio-group>
            <el-date-picker
              style="width: 200px; height: 40px; line-height: 40px"
              size="small"
              v-model="date"
              :type="
                this.radio == '日'
                  ? 'date'
                  : this.radio == '月'
                  ? 'month'
                  : 'year'
              "
              :format="
                this.radio == '日'
                  ? 'yyyy-MM-dd'
                  : this.radio == '月'
                  ? 'yyyy-MM'
                  : 'yyyy'
              "
              placeholder="选择时间"
            >
            </el-date-picker>
          </el-col>
          <el-col :span="13" style="text-align: right">
            <el-form-item>
              <Twobtn @chaxun="chaxun" @chongzhi="chongzhi"></Twobtn>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </div>
    <div class="bodybox">
      <div class="top">
        <div class="left" v-loading="loading1">
          <div class="tit">
            <img src="@/assets/image/sbnhzb.png" alt="" />设备能耗占Top10
          </div>
          <div v-if="e1" id="sbnhzb" style="width: 100%; height: 100%"></div>
        </div>
        <div class="right" v-loading="loading2">
          <div class="tit">
            <img src="@/assets/image/sbnhqs.png" alt="" />设备能耗趋势
          </div>
          <div v-if="e2" id="sbnhqs" style="width: 100%; height: 100%"></div>
        </div>
      </div>
      <div class="bottom" v-loading="loading3">
        <div class="top2">
          <div class="tit2">
            <img src="@/assets/image/sbfhqx.png" alt="" />设备负荷曲线Top10
          </div>
          <div class="tabs">
            <el-radio-group v-model="radio2">
              <el-radio-button label="主要设备"></el-radio-button>
              <el-radio-button label="辅助设备"></el-radio-button>
            </el-radio-group>
          </div>
        </div>
        <div v-if="e3" id="sbfhqx" style="width: 100%; height: 80%"></div>
      </div>
    </div>
  </div>
</template>

<script>
import * as echarts from 'echarts'
import {
  getCompanyListApi,
  getEnergyTrendApi,
  getLoadProfileApi,
  getProportionApi
} from '@/api/energy-consumption/Equipment-energy/Energy-analysis'
import dayjs from 'dayjs'
export default {
  name: 'EquipmentEnergyAnalysis',
  data() {
    return {
      radio: '日',
      radio2: '主要设备',
      form: {},
      date: null,
      loading1: false,
      loading2: false,
      loading3: false,
      companyList: [],
      ProportionList: [],
      EnergyTrendList: [],
      LoadProfileList: [],
      ProportionData: {},
      e1: true,
      e2: true,
      e3: true
    }
  },
  watch: {
    radio: {
      handler(newValue) {
        if (this.radio === '日') {
          this.date = dayjs().format('YYYY-MM-DD')
        } else if (this.radio === '月') {
          this.date = dayjs().format('YYYY-MM')
        } else if (this.radio === '年') {
          this.date = dayjs().format('YYYY')
        }
      },
      immediate: true
    },
    radio2: {
      async handler(newValue) {
        await this.getLoadProfile()
        this.myChart3()
      }
    },
    date: {
      handler(newValue) {
        if (this.radio === '日') {
          this.date = dayjs(newValue).format('YYYY-MM-DD')
          this.form.startDate = this.date
          this.form.endDate = this.date
        } else if (this.radio === '月') {
          this.date = dayjs(newValue).format('YYYY-MM')
          this.form.startDate = dayjs(this.date)
            .startOf('month')
            .format('YYYY-MM-DD')
          this.form.endDate = dayjs(this.date)
            .endOf('month')
            .format('YYYY-MM-DD')
        } else if (this.radio === '年') {
          this.date = dayjs(newValue).format('YYYY')
          this.form.startDate = dayjs(this.date)
            .startOf('year')
            .format('YYYY-MM-DD')
          this.form.endDate = dayjs(this.date)
            .endOf('year')
            .format('YYYY-MM-DD')
        }
      },
      immediate: true,
      deep: true
    }
  },
  async created() {
    await this.getCompanyList()
    await this.getdatalist()
  },
  methods: {
    companyChange(val) {
      localStorage.setItem('companyId', val)
    },
    // 获取用电企业列表
    async getCompanyList() {
      const res = await getCompanyListApi()
      console.log(res)
      this.companyList = res.data.list
      const companyId = +localStorage.getItem('companyId')
      if (companyId) {
        // this.bizOrgNo = companyId
        this.$set(this.form, 'companyId', companyId)
      } else {
        this.$set(this.form, 'companyId', this.companyList[0].id)
      }

      // this.$set(this.form, 'companyName', this.companyList[0].name)
    },
    // 初始化
    async getchushihua() {
      this.form.companyId = this.companyList[0].id
      localStorage.setItem('companyId', this.companyList[0].id)
      this.radio = '日'
      this.radio2 = '主要设备'
    },

    // 能耗占比饼图数据
    async getProportion() {
      this.e1 = false
      this.loading1 = true
      const res = await getProportionApi({
        companyId: this.form.companyId,
        // companyName: this.companyList.find((i) => i.id == this.form.companyId)
        //   .name,
        dateType: this.radio === '日' ? 1 : this.radio === '月' ? 2 : 3,
        startDate: this.form.startDate,
        endDate: this.form.endDate
      })
      console.log(res)
      this.ProportionList = res.data.list
      this.ProportionData = res.data.entity
      this.e1 = true
      this.loading1 = false
    },

    // 设备能耗趋势
    async getEnergyTrend() {
      this.e2 = false
      this.loading2 = true
      const res = await getEnergyTrendApi({
        companyId: this.form.companyId,
        dateType: this.radio === '日' ? 1 : this.radio === '月' ? 2 : 3,
        startDate: this.form.startDate,
        endDate: this.form.endDate
      })
      console.log(res)
      this.EnergyTrendList = res.data.list
      this.e2 = true
      this.loading2 = false
    },

    // 设备负荷曲线
    async getLoadProfile() {
      this.e3 = false
      this.loading3 = true
      const res = await getLoadProfileApi({
        companyId: this.form.companyId,
        dateType: this.radio === '日' ? '1' : this.radio === '月' ? '2' : '3',
        startDate: this.form.startDate,
        endDate: this.form.endDate,
        type: this.radio2 === '主要设备' ? '01' : '02'
      })
      console.log(res)
      this.LoadProfileList = res.data.list
      this.e3 = true
      this.loading3 = false
    },

    // 获取数据
    async getdatalist() {
      const promises = [
        this.getProportion().then(() => this.myChart1()),
        this.getEnergyTrend().then(() => this.myChart2()),
        this.getLoadProfile().then(() => this.myChart3())
      ]

      // 等待所有Promise完成
      await Promise.all(promises)
    },
    myChart1() {
      const data1 =
        this.ProportionList.length > 0
          ? this.ProportionList.map((i) => {
              return {
                name:
                  i.deviceName +
                  '\n' +
                  `用电量${i.valueReading.toFixed(2)}kWh,占比${i.valueRate}%`,
                value: i.valueRate
              }
            })
          : []
      // 内层环形图数据
      const subData1 = [
        {
          value: this.ProportionData.mainSum,
          name: '主要设备',
          itemStyle: { color: '#3ca0fe' }
        },
        {
          value: this.ProportionData.helperSum,
          name: '辅助设备',
          itemStyle: { color: '#f7c739' }
        }
      ]
      const myChart1 = echarts.init(document.getElementById('sbnhzb'))
      myChart1.setOption({
        legend: {
          type: 'scroll',
          orient: 'vertical', // 设置legend垂直排列
          left: 10,
          top: 30,
          height: '80%',
          data: data1.map((i) => i.name),
          formatter: function (name) {
            return name.split('\n')[0]
          }
        },
        series: [
          {
            type: 'pie',
            center: ['60%', '40%'],
            radius: ['50%', '70%'],
            avoidLabelOverlap: true,
            emphasis: {
              label: {
                show: true,
                fontSize: '20',
                fontWeight: 'bold'
              }
            },
            data: data1
          },
          {
            name: 'Inner',
            type: 'pie',
            center: ['60%', '40%'],
            radius: ['30%', '40%'],
            avoidLabelOverlap: true,
            label: {
              show: false,
              position: 'center'
            },
            emphasis: {
              label: {
                show: true,
                fontSize: '16',
                fontWeight: 'bold'
              }
            },
            labelLine: {
              show: false
            },
            data: subData1
          }
        ]
      })

      window.addEventListener('resize', () => {
        // 图表响应处理
        myChart1.resize()
      })
    },

    myChart2() {
      const data1 = {
        name: this.EnergyTrendList[0].name,
        type: 'bar',
        stack: 'Ad',
        emphasis: {
          focus: 'series'
        },
        data:
          this.EnergyTrendList[0].datalist.length > 0
            ? this.EnergyTrendList[0].datalist.map((obj) =>
                Number(obj.valueReading)?.toFixed(2)
              )
            : []
      }
      const data2 = {
        name: this.EnergyTrendList[1].name,
        type: 'bar',
        stack: 'Ad',
        emphasis: {
          focus: 'series'
        },
        data:
          this.EnergyTrendList[1].datalist.length > 0
            ? this.EnergyTrendList[1].datalist.map((obj) =>
                Number(obj.valueReading)?.toFixed(2)
              )
            : []
      }
      console.log(data1, data2)
      const myChart2 = echarts.init(document.getElementById('sbnhqs'))

      myChart2.setOption({
        tooltip: {
          trigger: 'axis',
          axisPointer: {
            type: 'shadow'
          }
        },
        legend: {},
        grid: {
          left: '3%',
          right: '4%',
          bottom: '3%',
          containLabel: true
        },
        xAxis: [
          {
            type: 'category',
            data:
              this.EnergyTrendList[0].datalist.length > 0
                ? this.EnergyTrendList[0].datalist.map((obj) => obj.timeReading)
                : []
          }
        ],
        yAxis: [
          {
            type: 'value'
          }
        ],
        series: [data1, data2]
      })
      window.addEventListener('resize', () => {
        // 图表响应处理
        myChart2.resize()
      })
    },

    myChart3() {
      const data =
        this.LoadProfileList.length > 0
          ? this.LoadProfileList.map((item) => {
              return {
                name: item.name,
                type: 'line',
                smooth: true,
                data: item.datalist.map((i) => [
                  i.timeReading,
                  i.valueReading?.toFixed(2)
                ])
              }
            })
          : [{ name: '', type: 'line', smooth: true, data: [] }]
      console.log(data)
      const myChart3 = echarts.init(document.getElementById('sbfhqx'))
      myChart3.setOption({
        tooltip: {
          trigger: 'axis'
        },
        legend: {
          type: 'scroll',
          orient: 'horizontal'
        },
        grid: {
          left: '3%',
          right: '4%',
          bottom: '0',
          // top: '5%',
          containLabel: true
        },
        xAxis: {
          type: 'category',
          boundaryGap: false
          // data: ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun']
        },
        yAxis: {
          type: 'value'
        },
        series: data
      })
      window.addEventListener('resize', () => {
        // 图表响应处理
        myChart3.resize()
      })
    },

    chaxun() {
      this.getdatalist()
    },

    async chongzhi() {
      await this.getchushihua()
      this.getdatalist()
    }
  }
}
</script>

<style lang="scss" scoped>
::v-deep .el-select {
  width: 100%;
}
.option {
  height: auto;
}
.dialog-footer {
  display: flex;
  justify-content: center;
}
.tit {
  display: flex;
  align-items: center;
  padding-left: 10px;
  margin-top: 10px;
  margin-bottom: -20px;
  font-weight: bold;
  img {
    margin-right: 10px;
  }
}

.bigbox {
  display: flex;
  flex-direction: column;
  padding: 10px;
  background-color: #f1f1f1;
  height: 100%;
  .topbox {
    background-color: #fff;
    padding: 20px 20px;
    box-sizing: border-box;
    height: 80px !important;
    width: 100% !important;
    margin-bottom: 10px;
    // transition-property: all;
    // transition-duration: 0.2s;

    .button {
      width: 63px;
      height: 32px;

      background-color: #fff;
      border: 1px solid #ccc;
      border-radius: 3px;
    }
    .chaxun {
      background-color: #1890ff;
      color: #fff;
    }
  }
  .bodybox {
    flex: 1;
    display: flex;
    flex-direction: column;
    .top {
      display: flex;
      height: 45%;
      width: 100%;
      margin-bottom: 10px;
      .left {
        background-color: #fff;
        margin-right: 10px;
        width: 45%;
      }
      .right {
        flex: 1;
        background-color: #fff;
      }
    }
    .bottom {
      flex: 1;
      background-color: #fff;
      .top2 {
        display: flex;
        justify-content: space-between;
        align-items: center;
        padding: 10px;
        .tit2 {
          display: flex;
          align-items: center;

          font-weight: bold;
          img {
            margin-right: 10px;
          }
        }
      }
    }
  }
}

// ::v-deep .el-form-item {
//   width: 100%;
//   margin-left: -10px;
// }

// ::v-deep .el-form-item__content {
//   width: calc(100% - 100px);
// }
// ::v-deep .el-col-6 {
//   height: 40px;
//   text-align: right;
// }
// ::v-deep .el-input__inner {
//   height: 32px;
// }
// ::v-deep.el-form--inline {
//   height: 100% !important;
//   box-sizing: border-box;
// }
// ::v-deep .el-radio-button__inner {
//   padding: 8px 20px;
// }
// ::v-deep .el-input__icon {
//   line-height: 20px;
// }
// button {
//   cursor: pointer;
// }
</style>
